//
//  MainViewController.m
//  maocuhuiOASystem
//
//  Created by michael on 16/3/20.
//  Copyright © 2016年 czd. All rights reserved.
//
#import "logTableViewController.h"
#import "txlTableViewController.h"

#import "houqinViewController.h"
#import "EatViewController.h"
#import "MeetingViewController.h"
#import "MainViewController.h"
#import "OALoginViewController.h"
#import "itemcell.h"
#import "OABaseNavViewController.h"
#import "ComingworkongController.h"
#import "emailViewController.h"
#import "iseditViewController.h"
#import "overworkingViewController.h"
#import "comingthingViewController.h"
#import "ideitworkViewController.h"
#import "workedViewController.h"
#import "OANewInViewController.h"
#import "OANewSendViewController.h"
#import "NotonewsViewController.h"
#import "webViewController.h"
#import "OAAddressViewController.h"
#import "OASMSViewController.h"
#import "MainViewCell.h"
#import "BaseModel.h"
#import "ReceieveViewController.h"
#import "AuthHelper.h"
#import "waitworkViewController.h"
#import "jinqijingbanViewController.h"
#import "xxxViewController.h"
#import "ViewController3.h"
#define kWB_Login_NotificationName @"requestdata"

@interface HomeModel : BaseModel

@property(nonatomic,copy)NSString *  exchange;
@property(nonatomic,copy)NSString *  ksmail;
@property(nonatomic,copy)NSString *  mail;
@property(nonatomic,copy)NSString *  offiece;
@property(nonatomic,copy)NSString *  whetherExchange;
@property(nonatomic,copy)NSString *  whetherSms;
@property(nonatomic,copy)NSString * read;
@end
@implementation HomeModel


@end
@interface MainViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property (nonatomic,strong) UIButton *button1;
@property (nonatomic,strong) UIButton *button2;
@property(nonatomic,strong)NSMutableArray * contentArray;
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *followLayout;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
//@property (nonatomic,strong) UICollectionView *collectionView;
@property(nonatomic,strong)HomeModel * homeModel;
@property(nonatomic,strong)NSMutableArray * originalData;
@property(nonatomic,strong)NSArray * array;
@property (nonatomic, strong) AuthHelper *helper;
@end

@implementation MainViewController
static NSString * const reuseIdentifier = @"CellIdentifier";
-(NSMutableArray*)contentArray{
    if (_contentArray == nil) {
        _contentArray = [NSMutableArray array];
    }
    return _contentArray;
}

- (void)viewDidLoad {
//short port = 443;                        //vpn设备端口号，一般为443
//NSString *vpnIp =    @"122.224.123.170";  //vpn设备IP地址
//    self.helper = [[AuthHelper alloc] initWithHostAndPort:vpnIp port:port delegate:self];
//    UIImageView *backImageView=[[UIImageView alloc]initWithFrame:self.view.bounds];
//       [backImageView setImage:[UIImage imageNamed:@"主页"]];
//        [self.view  addSubview: backImageView];
    [super viewDidLoad];
    if ([self respondsToSelector:@selector(automaticallyAdjustsScrollViewInsets)]) {
        self.automaticallyAdjustsScrollViewInsets = NO;
}
// 更改标题的颜色
//[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navBarBj"] forBarMetrics:UIBarMetricsDefault];
    NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:

[UIColor whiteColor],NSForegroundColorAttributeName, nil];
 
[self.navigationController.navigationBar setTitleTextAttributes:attributes];
self.title = @"瓯飞开发建设投资集团有限公司";
 self.navigationController.navigationBar.barTintColor = [UIColor blueColor];
   [self _backbutton];
//      [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"首页-标题"] forBarMetrics:UIBarMetricsDefault];
//   self.collectionView.height = KScreenHeight-64;
     self.followLayout.sectionInset = UIEdgeInsetsMake(30, 8, 8, 8);
    self.followLayout.itemSize = CGSizeMake(([UIScreen mainScreen].bounds.size.width - 50 )/ 4 , ([UIScreen mainScreen].bounds.size.width -25 )/ 3);
    self.followLayout.minimumLineSpacing = 20;
    UIImageView *view = [[UIImageView alloc]initWithFrame:self.view.frame];
view.image = [UIImage imageNamed:@"主页"];
//[self.view addSubview:view];

// 判断版本
[self upApp];
//定时器
     dispatch_async(dispatch_get_global_queue(0, 0), ^{
        _timer = [NSTimer scheduledTimerWithTimeInterval:300 target:self selector:@selector(news) userInfo:nil repeats:YES];
        // 开启当前线程
        [[NSRunLoop currentRunLoop] run];
    });

      //修改返回按钮的颜色和字体
  self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
//   UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleDone target:nil action:nil];
      UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"设置" style:UIBarButtonItemStyleDone target:nil action:nil];
    self.navigationItem.backBarButtonItem = barButtonItem;

}


- (void)dealloc
{
    // 移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kWB_Login_NotificationName object:nil];
    }
// 使用storyboard创建的控制调用的初始化方法
- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {
        // 注册通知
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(news) name:kWB_Login_NotificationName object:nil];
       
        
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated{
  [self news];
}
- (void)upApp{
 //获取app版本号
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *appVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    
    
    NSArray *array = @[@{@"veseion":appVersion}];

[HttpTools requestWithURL:KExchmain arrays:array method:@"updateDown" success:^(id JSON) {
         NSArray *tempArray  = JSON[@"data"];
        NSDictionary * dict = [tempArray firstObject];
            NSString *url = dict[@"downlink"];
        NSString *index = dict[@"result"];
    
    
    if ([index isEqualToString:@"1"]) {
            
// 提示更新
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"更新" message:@"程序已经更新，请卸载完以前的版本，再重新下载" preferredStyle:UIAlertControllerStyleAlert];

            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel  handler:^(UIAlertAction * _Nonnull action) {
                
//                  [_helper logoutVpn];
 UIStoryboard * storyBoard  =[UIStoryboard storyboardWithName:@"Main" bundle:nil];

    OALoginViewController * loginVC =  [storyBoard instantiateViewControllerWithIdentifier:@"LoginVC"];

    self.view.window.rootViewController = loginVC;
                
            }];

            UIAlertAction *action = [UIAlertAction actionWithTitle:@"更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                if (url.length != 0) {
                    
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];

                }
                
            }];
            
            [alert addAction:cancelAction];
            [alert addAction:action];
            
            [self presentViewController:alert animated:YES completion:nil];
            
            
            
            
        }

    }failure:^(NSError *error) {
        
    }];

    

}

- (void)news{
 NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray *  array = @[@{@"userId":userId}];;
    [HttpTools requestWithURL:KExchmain arrays:array method:KHomePqwoiunu success:^(id JSON) {
         NSArray *tempArray  = JSON[@"data"];
        NSDictionary * dict = [tempArray firstObject];
 
        self.homeModel = [[HomeModel alloc] initWitDictionary:dict];
                    [self setupSubView];

            [self.collectionView reloadData];

    } failure:^(NSError *error) {
        
    }];
    
    NSArray * array1 = @[@{@"userId":userId}];
    [HttpTools requestWithURL:Kexchmain arrays:array1 method:@"homeMailwoiunu" success:^(id JSON) {
    NSArray *dic = JSON[@"data"];
NSDictionary *dict = [dic firstObject];

    _reads = dict[@"mail"];
                [self.collectionView reloadData];

            } failure:^(NSError *error) {
        
    }];

    


}
-(void)setupSubView{
    if ([[_dic objectForKey:@"whetherExchange"] isEqualToString:@"0"]) {
          NSString * filePath =  [[NSBundle mainBundle] pathForResource:@"mainList1" ofType:@"plist"];
    self.originalData = [NSMutableArray arrayWithContentsOfFile:filePath];
    [self.contentArray addObjectsFromArray:self.originalData];    }
    
  else {
         NSString * filePath =  [[NSBundle mainBundle] pathForResource:@"mainList1" ofType:@"plist"];
    self.originalData = [NSMutableArray arrayWithContentsOfFile:filePath];
    [self.contentArray addObjectsFromArray:self.originalData];    }
    
    self.contentArray = [self.originalData mutableCopy];
    [self.collectionView reloadData];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.contentArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
MainViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    NSDictionary * dict = self.contentArray[indexPath.item];
    cell.dict = dict;

if ([dict[@"title"] isEqualToString:@"待办工作"]) {
        [cell.btnCount setTitle:self.homeModel.offiece forState:UIControlStateNormal];
        if ([self.homeModel.offiece integerValue] !=0) {
            cell.btnCount.hidden = NO;
        }else{
            cell.btnCount.hidden = YES;
        }
    }
    
    
    else if ([dict[@"title"]isEqualToString:@"政务公告"]) {
        [cell.btnCount setTitle:self.homeModel.ksmail forState:UIControlStateNormal];
        if ([self.homeModel.ksmail integerValue] !=0) {
            cell.btnCount.hidden = NO;
        }else{
            cell.btnCount.hidden = YES;
        }
        
    }

 else if ([dict[@"title"]isEqualToString:@"在办工作"]) {
        [cell.btnCount setTitle:self.homeModel.read forState:UIControlStateNormal];
        if ([self.homeModel.read integerValue] !=0) {
            cell.btnCount.hidden = NO;
        }else{
            cell.btnCount.hidden = YES;
        }
        
    }

    
    else if ([dict[@"title"] isEqualToString:@"电子邮件"]) {
        [cell.btnCount setTitle:self.homeModel.mail forState:UIControlStateNormal];
        if ([self.homeModel.mail integerValue] !=0) {
            cell.btnCount.hidden = NO;
        }else{
            cell.btnCount.hidden = YES;
        }
    }else{
        cell.btnCount.hidden = YES;
    }
    [cell layoutIfNeeded];
    return cell;

}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
// NSLog(@"cell #%ld was selected", (long)indexPath.row);
 NSDictionary * dict =  self.contentArray[indexPath.item];
  
   
//    if ([dict[@"title"] isEqualToString:@"公文收发"]) {
//
//      ReceieveViewController *comvc =(ReceieveViewController *) [self.storyboard instantiateViewControllerWithIdentifier:@"Receieve"];
//      comvc.string = [_dic objectForKey:@"exchange"];
//      
//    [self.navigationController pushViewController:comvc animated:YES];
//    
//    }
       if ([dict[@"title"] isEqualToString:@"待办工作"]) {
   ComingworkongController *wait =(ComingworkongController *) [self.storyboard instantiateViewControllerWithIdentifier:@"comvc"];
   
   wait.title = @"待办工作";
    [self.navigationController pushViewController:wait animated:YES];
    }
    if ([dict[@"title"] isEqualToString:@"在办工作"]) {
//     waitworkViewController *wait =(waitworkViewController *) [self.storyboard instantiateViewControllerWithIdentifier:@"wait"];
//     wait.string = @"在办工作";
//    [self.navigationController pushViewController:wait animated:YES];

    
  iseditViewController *isedvc =(iseditViewController *) [self.storyboard instantiateViewControllerWithIdentifier:@"isedit"];
  isedvc.title = @"在办工作";
    [self.navigationController pushViewController:isedvc animated:YES];
    
    }
    if ([dict[@"title"] isEqualToString:@"近期经办"]) {
    jinqijingbanViewController *vc = [[jinqijingbanViewController alloc]init];
    
    
//   overworkingViewController *overvc = (overworkingViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"over"];
    [self.navigationController pushViewController:vc animated:YES];
    }
    if ([dict[@"title"] isEqualToString:@"政务公告"]) {
   comingthingViewController *comthvc = (comingthingViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"comingthing"];
       [self.navigationController pushViewController:comthvc animated:YES];
    }
     if ([dict[@"title"] isEqualToString:@"食堂管理"]) {
   EatViewController *eat = (EatViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"eat"];
       [self.navigationController pushViewController:eat animated:YES];
    }

     if ([dict[@"title"] isEqualToString:@"会议室管理"]) {
    MeetingViewController *comthvc = (MeetingViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"meet"];

//   MeetingViewController *comthvc = [[MeetingViewController alloc]init];
       [self.navigationController pushViewController:comthvc animated:YES];

    }
 if ([dict[@"title"] isEqualToString:@"领导一周安排"]) {
xxxViewController *worked = [[xxxViewController alloc]init];
    [self.navigationController pushViewController:worked animated:YES];
    }


    if ([dict[@"title"] isEqualToString:@"后勤管理"]) {
     houqinViewController *ideitvc = [[houqinViewController alloc]init];
         [self.navigationController pushViewController:ideitvc animated:YES];
    }
    if ([dict[@"title"] isEqualToString:@"工作日志"]) {
     logTableViewController *ideitvc = [[logTableViewController alloc]init];
         [self.navigationController pushViewController:ideitvc animated:YES];
    }
    if ([dict[@"title"] isEqualToString:@"公文查询"]) {
workedViewController *worked = (workedViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"worked"];
    [self.navigationController pushViewController:worked animated:YES];
    }
    if ([dict[@"title"] isEqualToString:@"通知通告"]) {
     NotonewsViewController *notonews = (NotonewsViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"notonews"];
    [self.navigationController pushViewController:notonews animated:YES];    }
    if ([dict[@"title"] isEqualToString:@"电子邮件"]) {
   emailViewController  *email = (emailViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"email"];
email.reads = [NSString  stringWithFormat:@"%@",self.homeModel.mail] ;
    [self.navigationController pushViewController:email animated:YES];
    }
    if ([dict[@"title"] isEqualToString:@"最新收文"]) {
OANewInViewController *oAnewView =  (OANewInViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"OANewInView"];
   //OANewInView
    [self.navigationController pushViewController:oAnewView animated:YES];
    }
    if ([dict[@"title"] isEqualToString:@"最新发文"]) {
   OANewSendViewController *oAnewSend = (OANewSendViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"OANewIn"];
    [self.navigationController pushViewController:oAnewSend animated:YES];
    }
    if ([dict[@"title"] isEqualToString:@"通讯录"]) {
    txlTableViewController *vc = [[txlTableViewController alloc]init];
//   OAAddressViewController * addressVC = (OAAddressViewController*)[self.storyboard instantiateViewControllerWithIdentifier:@"AddressVCID"];
        [self.navigationController pushViewController:vc animated:YES];
    }
    
//     if ([dict[@"title"] isEqualToString:@"通讯录"]) {
//   OAAddressViewController * addressVC = (OAAddressViewController*)[self.storyboard instantiateViewControllerWithIdentifier:@"AddressVCID"];
//        [self.navigationController pushViewController:addressVC animated:YES];
//    }

    if ([dict[@"title"] isEqualToString:@"短信平台"]) {
   OASMSViewController *smvc = (OASMSViewController *)[ self.storyboard instantiateViewControllerWithIdentifier:@"SMSVCID"];
    [self.navigationController pushViewController:smvc animated:YES];
    }
    if ([dict[@"title"] isEqualToString:@"水利网站"]) {
  webViewController *webvc = [[webViewController alloc]init];
  webvc.url = @"http://www.wzsl.gov.cn";
[self.navigationController pushViewController:webvc  animated:YES];
  }
    if ([dict[@"title"] isEqualToString:@"水利微博"]) {
   webViewController *webvc = [[webViewController alloc]init];
   webvc.url = @"http://weibo.com/wzsslj/home?topnav=1&wvr=6";
[self.navigationController pushViewController:webvc  animated:YES];

    }
   }


- (void)_backbutton{
UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
rightButton.frame = CGRectMake(0, 0, 44, 44);
                [rightButton addTarget:self action:@selector(rightButtonAction:) forControlEvents:UIControlEventTouchUpInside];
//                    [rightButton setTitle:@"退出" forState:UIControlStateNormal];
              [rightButton setTitle:@"设置" forState:UIControlStateNormal];

                    [rightButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                 
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    UIButton *liftButton = [UIButton buttonWithType:UIButtonTypeCustom];
liftButton.frame = CGRectMake(0, 0,72*.6, 72*.6);
[liftButton setImage:[UIImage imageNamed:@"title_logo"] forState:UIControlStateDisabled];
 self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:liftButton];
 liftButton.enabled = NO;

    
    
}

- (void)rightButtonAction:(UIButton *)button {


ViewController3 *vc = [[ViewController3 alloc]init];
[self.navigationController pushViewController:vc animated:YES];

// UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:nil message:@"是否退出登录" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
//    [alertView show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{

if (buttonIndex == 1){
// [_helper logoutVpn];
 OALoginViewController * loginVC =  [self.storyboard instantiateViewControllerWithIdentifier:@"LoginVC"];
     [[NSUserDefaults standardUserDefaults] setObject:@"N" forKey:@"autoLogin"];
    self.view.window.rootViewController = loginVC;


}
}
@end
